package com.bangdream.michelia.view.activity.exam;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.bangdream.michelia.R;
import com.bangdream.michelia.application.AppCurrentUser;
import com.bangdream.michelia.contract.ExamContract;
import com.bangdream.michelia.entity.BaseEntity;
import com.bangdream.michelia.entity.exam.ExamBean;
import com.bangdream.michelia.entity.exam.ExamQuestBean;
import com.bangdream.michelia.entity.exam.ExamResultDetailsBean;
import com.bangdream.michelia.entity.exam.ExamResultItemBean;
import com.bangdream.michelia.entity.exam.SubjectBean;
import com.bangdream.michelia.entity.exam.SubjectInfoBean;
import com.bangdream.michelia.presenter.ExamPresenter;
import com.bangdream.michelia.tool.NoScrollViewPager;
import com.bangdream.michelia.tool.retrofithttp.RetroFactory;
import com.bangdream.michelia.tool.retrofithttp.TokenManagerDef;
import com.bangdream.michelia.utils.DateUtil;
import com.bangdream.michelia.utils.L;
import com.bangdream.michelia.utils.ToastUtil;
import com.bangdream.michelia.view.activity.base.BaseActivity;
import com.bangdream.michelia.view.fragment.exam.BaseAnswerFragment;
import com.bangdream.michelia.view.fragment.exam.ExamDefaultFragment;
import com.bangdream.michelia.view.fragment.exam.FillBlankFragment;
import com.bangdream.michelia.view.fragment.exam.SelectExamFragment;
import com.bangdream.michelia.view.fragment.exam.SolveFragment;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import okhttp3.MediaType;
import okhttp3.RequestBody;

/**
 * @date on 2018/8/18 17:05
 * @email 909732184@qq.com
 * 考试
 */
public class ExamActivity extends BaseActivity<ExamContract.IExamView,ExamPresenter<ExamContract.IExamView>>
        implements View.OnClickListener,ViewPager.OnPageChangeListener,ExamContract.IExamView,OnMainActivityListener {
    private NoScrollViewPager viewPager;
    private FragmentPagerAdapter mAdapter;
    private ImageView btnDtk;
    private TextView btnNext,btnLast;
    private List<BaseAnswerFragment> answerFragments = new ArrayList<>();
    private String stCountDown = "";
    //倒计时使用的被观察者
    private Observable<Long> mObservable;
    private Disposable disposable;
    //paperId 试卷id
    private String paperId;
    //考试id  每次考试都重新生成 同一套试卷两次考试id不同
    private String examId;
    private List<SubjectBean> data;
    private ExamBean examBean;
    boolean isPlan=false;
    String planUserItemId;


    //答题卡页面返回
    private final int AnswerCardActivityCode = 0x154;
    @Override
    public int getLayout() {
        return R.layout.activity_exam;
    }

    @Override
    public void findId() {
        viewPager = findViewById(R.id.viewPager);
        btnDtk = findViewById(R.id.btnDtk);
        btnNext = findViewById(R.id.btnNext);
        btnLast = findViewById(R.id.btnLast);
    }

    @Override
    public void setListener() {
        viewPager.addOnPageChangeListener(this);
        btnDtk.setOnClickListener(this);
    }

    @Override
    public void logic() {
        initTitleBar(" ","考试","交卷",this);
        if(getIntent().getExtras()!=null){
            paperId = getIntent().getStringExtra("paperId");
            examBean = getIntent().getExtras().getParcelable("data");
            isPlan = getIntent().getBooleanExtra("isPlan",false);
            planUserItemId = getIntent().getStringExtra("planUserItemId");

        }
        setHideInput(true);
        viewPager.setNoScroll(true);
        //先创建考试id 然后使用考试id去获取对应的题目集合
        if(paperId!=null){
            boolean isContinue = getIntent().getBooleanExtra("isContinue", false);

            if(isContinue){
                examId = getIntent().getStringExtra("examId");
                mPresenter.getSubjectList(this.examId, pd);
                if(isPlan){
                    bindExam(examId,planUserItemId);
                }
            }else{
                mPresenter.initExamId(paperId,pd);
            }

        }

    }

    private void bindExam(String examId, String planUserItemId){
        Map map=new HashMap();
        map.put("id", planUserItemId);
        map.put("examId", examId);

        String jsonString = JSON.toJSONString(map);
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"),jsonString);

        TokenManagerDef.work(() ->
                RetroFactory.getInstance().bindExamByTran(AppCurrentUser.getInstance().getToken(),requestBody))
                .compose(TokenManagerDef.newInstance().getTransformer())
                .compose(composeFunction)
                .subscribe(new Observer<BaseEntity>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(BaseEntity o) {
                        if(o.isOk()){

                        }else{
                            ToastUtil.showShortToast(ExamActivity.this,"绑定任务计划失败");
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        ToastUtil.showShortToast(ExamActivity.this,"绑定任务计划失败");
                    }

                    @Override
                    public void onComplete() { }
                });
    }

    @Override
    public ExamPresenter createPresenter() {
        return new ExamPresenter();
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {

    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.tv_left:
                AlertDialog.Builder builder = new AlertDialog.Builder(ExamActivity.this);
                builder.setMessage("是否提交问卷？");
                //    设置一个PositiveButton
                builder.setPositiveButton("确定", new DialogInterface.OnClickListener()
                {
                    @Override
                    public void onClick(DialogInterface dialog, int which)
                    {
                        isRefresh = true;
                        answerFragments.get(viewPager.getCurrentItem()).saveAnswer(true,false);
                    }
                });
                builder.setNegativeButton("取消", new DialogInterface.OnClickListener()
                {
                    @Override
                    public void onClick(DialogInterface dialog, int which)
                    {
//                    Toast.makeText(MainActivity.this, "negative: " + which, Toast.LENGTH_SHORT).show();
                        dialog.dismiss();
                        finish();
                    }
                });
                builder.show();
                break;
            case R.id.btnLast:
                answerFragments.get(viewPager.getCurrentItem()).saveAnswer(false,false);
                break;
            case R.id.btnNext:
                //如果点击的是最后一题的下一题 触发交卷
                if(viewPager.getCurrentItem()==mAdapter.getCount()-1){
                    onClick(tv_right);
                    return;
                }
                answerFragments.get(viewPager.getCurrentItem()).saveAnswer(false,true);
                break;
            case R.id.tv_right:
                isRefresh = true;
                if(viewPager.getCurrentItem()!=0){
                    answerFragments.get(viewPager.getCurrentItem()).saveAnswer(true,false);
                }
                break;
            case R.id.btnDtk:
                Intent intent = new Intent(this,AnswerCardActivity.class);
                if(viewPager==null)
                    return;
                intent.putExtra("index",viewPager.getCurrentItem());
                startActivityForResult(intent,AnswerCardActivityCode);
                break;
                default:break;
        }
//        super.onClick(view);
    }

    private void setTitleText(){
        if(data==null||viewPager==null)
            return;
        SubjectBean subjectBean = data.get(viewPager.getCurrentItem());
        if(subjectBean==null)
            return;
        tv_title.setText(subjectBean.getQuestionTitle()+"");
    }
    /**
     * 开始计时 考试时间倒计时
     */
    private void startTime(final long count){
        mObservable = Observable.interval(0,1, TimeUnit.SECONDS)//延时几秒，每隔几秒开始执行
                //超过多少秒停止执行
                .take(count + 1)
                //类型转换，由于是倒计时，案例需要将倒计时的数字反过来
                .map(new Function<Long, Long>() {
                    @Override
                    public Long apply(@NonNull Long aLong) {
                        //MyLog.d("apply",aLong+"=aLong\n"+(count - aLong));
                        return count - aLong;
                    }
                })
                //观察者在主线程执行
                .observeOn(AndroidSchedulers.mainThread())
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(@NonNull Disposable disposable) throws Exception {
                        L.d("倒计时执行过程中");
                    }
                });

        //设置订阅观察者
        mObservable.subscribe(new Observer<Long>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        L.d("倒计时开始执行");
                        disposable = d;
                    }

                    @Override
                    public void onNext(Long aLong) {
                        L.d("剩余" + aLong + "秒");
                        stCountDown = DateUtil.formart2(aLong);
                        updataSurplusTime();
                    }

                    @Override
                    public void onError(Throwable e) {
                        L.e("倒计时执行出错："+e.toString());
                        showText("抱歉计时器出错");
                        finish();
                    }

                    @Override
                    public void onComplete() {
                        L.d("执行完毕");
                        onClick(tv_right);
                    }
                });

    }
    //更新显示的剩余时间
    private void updataSurplusTime(){
        if(answerFragments!=null && answerFragments.size()>0) {
            BaseAnswerFragment baseAnswerFragment = answerFragments.get(viewPager.getCurrentItem());
            answerFragments.get(viewPager.getCurrentItem()).setTime(stCountDown);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ExamHelper.getInstance().clean();
        if(disposable!=null){
            //取消掉计时器的订阅
            disposable.dispose();
        }
    }

    @Override
    public void setExamList(boolean isSuccess, int page, List<ExamBean> data, String stDescribe) {

    }

    @Override
    public void setSubjectList(boolean isSuccess, List<SubjectBean> data, String stDescribe) {
        if(isSuccess){
            this.data = data;
            setViewData();
            setTitleText();
        }
    }

    @Override
    public void setSubjectDetails(boolean isSuccess, SubjectInfoBean data, String stDescribe) {

    }

    @Override
    public void initExamId(boolean isSuccess, String examId, String stDescribe) {
        if(isSuccess&&examId!=null) {
            this.examId = examId;
            mPresenter.getSubjectList(this.examId, pd);
            if(isPlan){
                bindExam(examId,planUserItemId);
            }
        }
    }

    @Override
    public void actionSubmitExam(boolean isSuccess,boolean isFinish, String stDescribe) {

    }

    @Override
    public void actionSubmitQuest(boolean isSuccess, boolean isFinish, String stDescribe) {

    }

    @Override
    public void setExamResultList(boolean isSuccess, List<ExamResultItemBean> data, String stDescribe) {

    }

    @Override
    public void setExamResultDetails(boolean isSuccess, ExamResultDetailsBean data, String stDescribe) {

    }

    @Override
    public void setExamQuestList(boolean isSuccess, List<ExamQuestBean> data, String stDescribe) {

    }

    @Override
    public void setExamQuList(boolean isSuccess, List<ExamBean> data, String stDescribe) {

    }

    private void setViewData() {

        if(examBean==null||data==null) {
            return;
        }
        if(data.size()==1){
            btnNext.setText("提交试卷");
        }else{
            btnNext.setText("下一题");
        }
        for(int i = 0;i<data.size();i++) {
            ExamHelper.getInstance().getIsAnswerBegin().add(false);
        }
        /**
         * 初始化Adapter
         */
        mAdapter = new FragmentPagerAdapter(getSupportFragmentManager()){

            @Override
            public int getCount() {
                return  data.size();
            }

            @Override
            public Fragment getItem(int position) {
                Bundle bundle = new Bundle();
                bundle.putInt("index",position);
                bundle.putInt("totalIndex",getCount());
                bundle.putString("examId",examId);
                bundle.putString("paperId",paperId);
                bundle.putParcelable("data",data.get(position));
                BaseAnswerFragment answerFragment = null;
                SubjectBean subjectBean = data.get(position);
                if(subjectBean==null||subjectBean.getQuestionType()==null){
                    return null;
                }

                if(subjectBean.getQuestionType().equals(SubjectType.write.getValue())){
                    //填空题
                    answerFragment = new FillBlankFragment();
                }else if(subjectBean.getQuestionType().equals(SubjectType.multiSelection.getValue())){
                    //多选题
                    answerFragment = new SelectExamFragment();
                    bundle.putBoolean("isSingle",false);
                }else if(subjectBean.getQuestionType().equals(SubjectType.selection.getValue())){
                    //单选题
                    answerFragment = new SelectExamFragment();
                    bundle.putBoolean("isSingle",true);
                }else if(subjectBean.getQuestionType().equals(SubjectType.shortexam.getValue())){
                    //简答题
                    answerFragment = new SolveFragment();
                }else if (subjectBean.getQuestionType().equals(SubjectType.judgement.getValue())){
                    //判断题使用和单选题意义的界面
                    answerFragment = new SelectExamFragment();
                    bundle.putBoolean("isSingle",true);
                }else {
                    //未知题型
                    answerFragment = new ExamDefaultFragment();
                }
                answerFragment.setOnMainActivityListener(ExamActivity.this);
                answerFragment.setArguments(bundle);
                answerFragments.add(answerFragment);
                return answerFragment;
            }
        };
        //每个页面都缓存 不用每次划开重新加载
        viewPager.setOffscreenPageLimit(data.size());
        viewPager.setAdapter(mAdapter);
        int time = 0;
        try {
            time = Integer.parseInt(examBean.getTime());
        }catch (Exception e){
            L.e(e.toString());
        }
        startTime(time*60);
    }


    @Override
    public void onPageToNext() {
        viewPager.setCurrentItem(viewPager.getCurrentItem()+1);
        answerFragments.get(viewPager.getCurrentItem()).setTime(stCountDown);
        setTitleText();
        changeText();
    }

    @Override
    public void onPageToLast() {
        viewPager.setCurrentItem(viewPager.getCurrentItem()-1);
        answerFragments.get(viewPager.getCurrentItem()).setTime(stCountDown);
        setTitleText();
        changeText();
    }

    private void changeText(){
        if(viewPager.getCurrentItem()>0){
            btnLast.setVisibility(View.VISIBLE);
        }else{
            btnLast.setVisibility(View.GONE);
        }
        if(viewPager.getCurrentItem()==(mAdapter.getCount()-1)){
            btnNext.setText("提交试卷");
        }else{
            btnNext.setText("下一题");
        }
    }


    public enum SubjectType{
        //多选 单选 填空 简答 判断
        multiSelection{public String getValue(){ return "multiSelection"; }}
        ,selection{public String getValue(){ return "selection"; }}
        ,write{public String getValue(){ return "write"; }}
        ,shortexam{public String getValue(){ return "short"; }}
        ,judgement{public String getValue(){ return "judgement"; }};
        public abstract String getValue();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK)) {
            AlertDialog.Builder builder = new AlertDialog.Builder(ExamActivity.this);
            //    设置Title的内容
//            builder.setTitle("弹出警告框");
            //    设置Content来显示一个信息
            builder.setMessage("是否提交问卷？");
            //    设置一个PositiveButton
            builder.setPositiveButton("确定", new DialogInterface.OnClickListener()
            {
                @Override
                public void onClick(DialogInterface dialog, int which)
                {
                    isRefresh = true;
                    answerFragments.get(viewPager.getCurrentItem()).saveAnswer(true,false);
                }
            });
            builder.setNegativeButton("取消", new DialogInterface.OnClickListener()
            {
                @Override
                public void onClick(DialogInterface dialog, int which)
                {
//                    Toast.makeText(MainActivity.this, "negative: " + which, Toast.LENGTH_SHORT).show();
                    dialog.dismiss();
                    finish();
                }
            });
            builder.show();
            return false;
        } else {
            return super.onKeyDown(keyCode, event);
        }


    }

        @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode!= Activity.RESULT_OK)
            return;
        switch (requestCode){
            case AnswerCardActivityCode:
                int index = data.getIntExtra("index",-1);
                if(index!=-1){
                    viewPager.setCurrentItem(index);
                }
                break;
                default:break;
        }
    }
}
